<?php
include("sajax.php");
include("config_db.php");

function autenticarHTTP(){
	header('WWW-Authenticate: Basic realm="SPPSBO:'.md5(time()).'"');
	header('HTTP/1.0 401 Unauthorized');
	header('refresh:5;url="/sppsbo/"');
	echo utf8_decode('Você deve usar um login e uma senha válidos para acessar esse recurso.');
	exit;
}
function deslogarUsuario(){
	session_start();
	session_regenerate_id();
	session_destroy();
	unset($_SESSION);
	unset($_SERVER['PHP_AUTH_USER']);
	unset($_SERVER['PHP_AUTH_PW']);
	session_start();
}
function autenticarUsuario(){
	session_start();
	if(!isset($_SERVER['PHP_AUTH_USER'])){
		autenticarHTTP();
	} else {
		$cpf = mysql_real_escape_string($_SERVER['PHP_AUTH_USER']);
		$sql = "select CPF, Senha from funcionarios where CPF like $cpf;";
		if(!$result = mysql_query($sql)){
			autenticarHTTP();
		}
		$row = mysql_fetch_assoc($result);
		if($row['Senha'] != md5($_SERVER['PHP_AUTH_PW'])){
			autenticarHTTP();
		}
	}
}
/**
** Salva dos dados da tela de Cadastro de Funcionário. (201102121606)
**/
function Save($dados){
	$dados = mysql_real_escape_string($dados);
	$dados = explode(",",$dados);
	$nome = $dados[0];
	$cpf = $dados[1];
	$fone = $dados[2];
	$senha = md5($dados[3]);
	$sql = "insert into funcionarios (`Nome`,`CPF`,`Telefone`,`Senha`) values ('{$nome}','{$cpf}','{$fone}','{$senha}');";
	if($result = mysql_query($sql)){
		$retorno = "Funcionário cadastrado.";
	} else {
		$retorno = "Problema ao cadastrar.";
	}	
	return $retorno;
}
function getIP(){
	$ip = (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown'); 
	$forward = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR']:false);
	$ip = (($ip=='unknown' &&  $foward && $forward!='unknown' )?$forward:$ip);
	return gethostbyname($ip);
}
function setPonto($cpf){
	$endereco = getIP();
	$cpf = mysql_real_escape_string($cpf);
	$result = mysql_query("select CPF from funcionarios where CPF like $cpf;") or die(mysql_error());
	$row = mysql_fetch_assoc($result);	
	if($row['CPF'] == $cpf){
		$sql = "insert into spp_pontos ( `horario`,`cpf`,`endereco` ) values ( NOW(),'{$cpf}','{$endereco}' );";
		$result = mysql_query($sql) or die(mysql_error());
		$retorno = 1;
	} else {
		$retorno = 0;
	}
	return $retorno;
}

function getFunc($cpf) {
	$cpf = mysql_real_escape_string($cpf);
	$result = mysql_query("select * from funcionarios where CPF like '{$cpf}%' ;")or die(mysql_error());
	$row = mysql_fetch_assoc($result);
	return utf8_encode($row["Nome"]);
}
function getCPF($cpf) {
	$cpf = mysql_real_escape_string($cpf);
	$result = mysql_query("select * from funcionarios where CPF like '{$cpf}%' ;")or die(mysql_error());
	$row = mysql_fetch_assoc($result);
	if (!empty($row["CPF"])){
		$out = substr($row["CPF"],-11,-8).'.'.substr($row["CPF"],-8,-5).'.'.substr($row["CPF"],-5,-2).'-'.substr($row["CPF"],-2);
	}	
	#return $out;
}
function getTime($cpf){
	return date('d/m/Y h:i');
}

sajax_init();
$sajax_debug_mode = 0;
sajax_export('getFunc','getCPF','getTime','setPonto','Save');
sajax_handle_client_request();

if($_GET['tela']==2){
	autenticarUsuario();
} else {
	deslogarUsuario();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sistema de Ponto da People SBO</title>
<link href="estilos.css" rel="stylesheet" type="text/css" />
<script><?php sajax_show_javascript(); ?></script>
</head>

<body>
<div id="menu">
	<ul>
		<li><a href="?tela=1">Coleta</a>&nbsp;|&nbsp;</li>
		<li><a href="?tela=2">Cadastro</a></li>
	</ul>
</div>
<?php
switch ($_GET['tela']) {
	case '2':
		include("cadastro.php");
	break;
	default:
		include("coleta.php");
	break;
}

/**
** Testes
*******************************************
	$cpf = '16788960801';
	$ip = $_SERVER['REMOTE_ADDR'];
	$cpf = mysql_real_escape_string($cpf);
	$result = mysql_query("select CPF from funcionarios where CPF like $cpf;") or die(mysql_error());
	$row = mysql_fetch_assoc($result);	
	if($row['CPF'] == $cpf){
		$sql = "insert into spp_pontos (horario,cpf,endereco) values (NOW(),'{$cpf}','{$ip}');";
		$result = mysql_query($sql) or die(mysql_error());
		$retorno = 1;
	} else {
		$retorno = 0;
	}
	print($cpf.'<br />'.$endereco.'<br />'.$result.'<br />'.$row['CPF'].'<br />'.$sql.'<br />'.$retorno.'<br />');
	
	echo $ip.'<br />';
	echo gethostbyname($_SERVER['REMOTE_ADDR']);
	
	echo Save('Hads','1234');
/********************************************
** Testes
**/
?>
</body>
</html>